#include "StompedReality/Core/FileSystem.h"
#ifdef WIN32
#include <io.h>
#else // ifdef WIN32
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#endif // ifdef WIN32
#include <fstream>
#include <iostream>
#include <string.h>
namespace StompedReality
{
namespace Utility
{
FileSystem::FileSystem( )
{
  this->m_BasePath = ".";
}

FileSystem::~FileSystem( )
{
}

void FileSystem::setBasePath ( std::string basePath )
{
  this->m_BasePath = basePath;
}

std::string FileSystem::getBasePath( )
{
  return this->m_BasePath;
}

bool FileSystem::existsFile ( std::string fileName )
{
  std::ifstream file ( this->m_BasePath + "/" + fileName );
  return file.is_open( );
}

bool FileSystem::existsFile ( FileInfo fileInfo )
{
  return this->existsFile( fileInfo.path +"/" + fileInfo.name );
}

JsonPTR FileSystem::openAsJson ( std::string fileName )
{
  JsonPTR jsonPtr( new Json::Value( ));
  std::ifstream file ( this->m_BasePath + "/" + fileName );
  if ( file.is_open( ) )
  {
    Json::Reader reader;
    reader.parse ( file, *jsonPtr );
  }
  return jsonPtr;
}

JsonPTR FileSystem::openAsJson ( FileInfo fileInfo )
{
  return this->openAsJson( fileInfo.path +"/" + fileInfo.name );
}

JsonPTR FileSystem::openAsJsonAbsolute ( std::string fileName )
{
  JsonPTR jsonPtr( new Json::Value( ));
  std::ifstream file ( fileName );
  if ( file.is_open( ) )
  {
    Json::Reader reader;
    reader.parse ( file, *jsonPtr );
  }
  return jsonPtr;
}


void FileSystem::saveJsonAbsolute ( Json::Value value, std::string fileName )
{
  std::ofstream oFile ( fileName );
  if ( oFile.is_open( ) )
  {
    Json::StyledStreamWriter sw;
    sw.write( oFile, value );

  }
}

void FileSystem::saveJson ( Json::Value value, std::string fileName )
{
  std::ofstream oFile ( this->m_BasePath + "/" + fileName );
  if ( oFile.is_open( ) )
  {
    Json::StyledStreamWriter sw;
    sw.write( oFile, value );

  }
}

}
}
